package org.apache.dolphinscheduler.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.api.client.util.Lists;
import org.apache.dolphinscheduler.api.enums.Status;
import org.apache.dolphinscheduler.api.service.CouponService;
import org.apache.dolphinscheduler.api.service.CouponbillService;
import org.apache.dolphinscheduler.api.service.UserGroupService;
import org.apache.dolphinscheduler.api.service.UsersService;
import org.apache.dolphinscheduler.api.utils.PageInfo;
import org.apache.dolphinscheduler.api.utils.Result;
import org.apache.dolphinscheduler.dao.entity.*;
import org.apache.dolphinscheduler.dao.mapper.CoupondetailMapper;
import org.apache.dolphinscheduler.dao.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;

import java.time.LocalDate;
import java.time.YearMonth;

import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalAdjusters;
import java.util.*;

/**
 * <p>
 * 收支明细表 服务实现类
 * </p>
 *
 * @author denggh
 * @since 2023-08-14
 */
@Service
public class CouponServiceImpl extends BaseServiceImpl implements CouponService {

    @Autowired
    private CoupondetailMapper coupondetailMapper;
    @Autowired
    private UsersService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserGroupService userGroupService;
    @Autowired
    private CouponbillService couponbillService;

    public void createCouponDetail(User loginUser, Coupondetail coupondetail) {
        if (coupondetail.getUseTimeType() == 1) {
            coupondetail.setIssueType("平台发放");
        } else if (coupondetail.getUseTimeType() == 2) {
            coupondetail.setIssueType("用户领取");
        }
        Date currentTime = new Date();
        coupondetail.setUpdateTime(currentTime);

        coupondetail.setCouponNo(String.valueOf(System.currentTimeMillis()));
        Date dateStr = coupondetail.getSendStartTime();
        Date dateStr1 = coupondetail.getSendEndTime();
        Date dateStr2 = coupondetail.getUseStartTime();
        Date dateStr3 = coupondetail.getUseEndTime();
        coupondetail.setSendStartTime(dateStr);
        coupondetail.setSendEndTime(dateStr1);
        coupondetail.setUseStartTime(dateStr2);
        coupondetail.setUseEndTime(dateStr3);
        coupondetail.setUseNum(0);
        coupondetail.setIssuer(loginUser.getId());

        coupondetailMapper.insert(coupondetail);
    }

    @Override
    public Result selectPageCoupondetailList(User loginUser, Integer pageSize, Integer pageNo,String couponName,Integer Type) {
        Result result = new Result();
        PageInfo<Coupondetail> pageInfo = new PageInfo<>(pageNo, pageSize);

        Page<Coupondetail> page = new Page<>(pageNo, pageSize);

        IPage<Coupondetail> coupondetailIPage = null;
        LambdaQueryWrapper<Coupondetail> lqw = new LambdaQueryWrapper<>();

        List<Integer> userIdList = Lists.newArrayList();
        // 如果不是管理员角色 只能查询当前用户收支明细
        // 如果用户是用户组管理员 可以查询用户组下所有用户的数据
        if (!isAdmin(loginUser)) {
            userIdList.add(loginUser.getId());
            List<Integer> userIds = userGroupService.queryAllUserByGroupAdmin(loginUser);
            if (CollectionUtils.isNotEmpty(userIds)) {
                userIdList.addAll(userIds);
            }
        }
        if (Objects.nonNull(couponName)&&!("".equals(couponName))){
            lqw.like(Coupondetail::getCouponName, couponName);
        }
        if (Objects.nonNull(Type)&&!("".equals(Type))){
            lqw.eq(Coupondetail::getType, Type);
        }
        if (userIdList != null && !userIdList.isEmpty()) {
            lqw.in(Coupondetail::getIssuer, userIdList);
        }
        coupondetailIPage = coupondetailMapper.selectPage(page, lqw);

        List<Coupondetail> couponLists = coupondetailIPage.getRecords();

        for(Coupondetail couponList : couponLists){
            String str;
            if(couponList.getUseRuleType()==1){str="单笔满";}
            else{str="每满";}
           couponList.setRule(str+ couponList.getUseRule() +"元可用");
            //couponList.setUseRule(couponList.getUseRule());
        }
        pageInfo.setTotal((int) coupondetailIPage.getTotal());
        pageInfo.setTotalList(couponLists);
        result.setData(pageInfo);
        putMsg(result, Status.SUCCESS);
        return result;
    }

    @Override
    public Map<String, Object> deleteCouponDetailById(int couponDetailId) {
        Map<String, Object> result = new HashMap<>();
        int delete = coupondetailMapper.deleteById(couponDetailId);
        if (delete > 0) {
            putMsg(result, Status.SUCCESS);
        }
        return result;
    }

    @Override
    public Map<String, Object> updateCouponDetail(Coupondetail coupondetail) {
        Map<String, Object> result = new HashMap<>();
        Date now = new Date();
        coupondetail.setUpdateTime(now);
        System.out.println(coupondetail.getUseEndTime());
        int update = coupondetailMapper.updateById(coupondetail);
        Coupondetail coupondetail1 = coupondetailMapper.selectById(coupondetail.getId());
        if(coupondetail1.getUseTimeType() == 1 && coupondetail1.getType() == 6)  //固定时间发放
        {
            Integer sendNum = couponbillService.addCouponBillByTimeTask(coupondetail.getId());
            coupondetail1.setSendNum(sendNum);
            coupondetailMapper.updateById(coupondetail1);
        }
        if (update > 0) {
            putMsg(result, Status.SUCCESS);
        }
        return result;
    }

    @Override
    public Result selectCouponTotal(User loginUser, String month){
        Result result = new Result();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M"); // 设置日期格式
        TemporalAccessor accessor = formatter.parse(month);
        YearMonth yearMonth = YearMonth.from(accessor);
        LocalDate localDate = yearMonth.atDay(1);
        //LocalDate localDate = LocalDate.parse(month, formatter);
        String firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth()).toString();
        String lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth()).toString();

        List<Integer> coupon=new ArrayList<>();
        Integer a=coupondetailMapper.countCouponType(1, firstDayOfMonth, lastDayOfMonth);
        Integer b=coupondetailMapper.countCouponType(2, firstDayOfMonth, lastDayOfMonth);
        coupon.add(a);
        coupon.add(b);
        result.setData(coupon);
        putMsg(result, Status.SUCCESS);
        return result;
    }

    @Override
    public Result selectCouponAmountTotal(User loginUser, String month) {
        Result result = new Result();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-M-d"); // 设置日期格式
        System.out.println(month);
        LocalDate localDate = LocalDate.parse(month+"-1", formatter);
        String firstDayOfMonth = localDate.with(TemporalAdjusters.firstDayOfMonth()).toString();
        String lastDayOfMonth = localDate.with(TemporalAdjusters.lastDayOfMonth()).toString();

        List<Map<String,Object>> resultList = coupondetailMapper.countCouponAmountTotal(firstDayOfMonth, lastDayOfMonth);
        result.setData(resultList);
        putMsg(result, Status.SUCCESS);
        return result;
    }

    @Override
    public Coupondetail getCouponDetailById(Integer id) {
        Coupondetail coupondetail = coupondetailMapper.selectById(id);
        return coupondetail;
    }
}
